﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace $rootnamespace$.admin.access
{
    public partial class Users_By_Role : System.Web.UI.Page
    {
        protected override void OnInit(EventArgs e)
        {
            UserRoles.DataSource = Roles.GetAllRoles();
            UserRoles.DataBind();
        }

        protected override void OnPreRender(EventArgs e)
        {
            /*
             * Dan Clem, 3/7/2007 and 4/27/2007.
             * The logic here is necessitated by the limitations of the built-in object model.
             * The Membership class does not provide a method to get users by role.
             * The Roles class DOES provide a GetUsersInRole method, but it returns an array of UserName strings
             * rather than a proper collection of MembershipUser objects.
             * 
             * This is my workaround.
             * 
             * Note to self: the two-collection approach is necessitated because you can't remove items from a collection
             * while iterating through it: "Collection was modified; enumeration operation may not execute."
             */

            MembershipUserCollection allUsers = Membership.GetAllUsers();
            MembershipUserCollection filteredUsers = new MembershipUserCollection();

            if (UserRoles.SelectedIndex > 0)
            {
                string[] usersInRole = Roles.GetUsersInRole(UserRoles.SelectedValue);
                foreach (MembershipUser user in allUsers)
                {
                    foreach (string userInRole in usersInRole)
                    {
                        if (userInRole == user.UserName)
                        {
                            filteredUsers.Add(user);
                            break; // Breaks out of the inner foreach loop to avoid unneeded checking.
                        }
                    }
                }
            }
            else
            {
                filteredUsers = allUsers;
            }
            Users.DataSource = filteredUsers;
            Users.DataBind();
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        //public string GetCurrentPageName()
        //{
        //    string Path = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
        //    System.IO.FileInfo Info = new System.IO.FileInfo(Path);
        //    string pageName = Info.Name;
        //    return pageName;
        //}
    }
}